package com.fzq.flowable_demo.config; // 根据您的包结构调整

import ch.qos.logback.core.PropertyDefinerBase;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * 获取本机ip
 */
public class IPPropertyDefiner extends PropertyDefinerBase {

    private String type = "external"; // 可选: external, internal, localhost

    public void setType(String type) {
        this.type = type;
    }

    @Override
    public String getPropertyValue() {
        try {
            if ("localhost".equals(type)) {
                return InetAddress.getLocalHost().getHostAddress();
            } else if ("internal".equals(type)) {
                return getInternalIP();
            } else {
                return getExternalIP();
            }
        } catch (Exception e) {
            return "0.0.0.0";
        }
    }

    private String getInternalIP() throws SocketException {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface iface = interfaces.nextElement();
            // 跳过回环和虚拟接口
            if (iface.isLoopback() || iface.isVirtual() || !iface.isUp()) {
                continue;
            }

            Enumeration<InetAddress> addresses = iface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress addr = addresses.nextElement();
                // 只返回IPv4地址
                if (addr.getAddress().length == 4) {
                    return addr.getHostAddress();
                }
            }
        }
        return "0.0.0.0";
    }

    private String getExternalIP() {
        // 注意: 获取外部IP通常需要调用外部服务
        // 这里简化处理，返回内部IP
        try {
            return getInternalIP();
        } catch (Exception e) {
            return "0.0.0.0";
        }
    }
}